const fetch = require('node-fetch');
const retry = require('bluebird-retry');
const {HttpsProxyAgent} = require('https-proxy-agent')
require('dotenv').config()

const isOpenProxy = process.env.is_open_proxy || 1;
const agent = isOpenProxy == 1 ? new HttpsProxyAgent('http://127.0.0.1:7890') : null;
const rpc = 'https://open-api.unisat.io';
const apiKey = 'd9f564947d5137a71cd87958fe5a59fdf65dae05b7a7c2041259fbe16a7afcb3';
function UnisatAPI() {
    let self = this;
    self.rpc = rpc;
    self.Authorization = `Bearer ${apiKey}`;
    self.agent = agent;
    self.headers = { 
        'Content-Type': 'application/json',
        'Authorization': self.Authorization
    };
}

UnisatAPI.prototype.getAddressBrc20HistoryCount = async function ({address, ticker, type=''}) {
  let self = this;
  let url = `${rpc}/v1/indexer/address/${address}/brc20/${ticker}/history?start=0&limit=1`;
  if (type.length > 0 ) {
    url = `${url}&type=${type}`
  }
  const response = await fetch(url, {
      method: 'GET',
      headers: self.headers,
      agent: self.agent
    });
    let res = await response.json();
    if (res.code == 0) {
      let total = parseInt(res.data.total);
      return total;
    } else {
      throw(new Error(res.msg))
    }
    return res;
}

UnisatAPI.prototype.getAddressBrc20History = async function ({address, ticker, start=0, limit=10000, type=''}) {
    let self = this;
    let url = `${rpc}/v1/indexer/address/${address}/brc20/${ticker}/history?start=${start}&limit=${limit}`;
    if (type.length > 0 ) {
      url = `${url}&type=${type}`
    }
    const response = await fetch(url, {
        method: 'GET',
        headers: self.headers,
        agent: self.agent
      });
      let res = await response.json();
      if (res.code == 0) {
        let total = parseInt(res.data.total);
        let a = res.data.detail;
        return a;
      } else {
        throw(new Error(res.msg))
      }
      return res;
}

UnisatAPI.prototype.getBrc20HolderNumber = async function (ticker) {
  let self = this;
    let url = `${rpc}/v1/indexer/brc20/${ticker}/holders?start=0&limit=1`;
    
    const response = await fetch(url, {
        method: 'GET',
        headers: self.headers,
        agent: self.agent
      });
      let res = await response.json();
      return res.data.total;

}

UnisatAPI.prototype.getBrc20Holder = async function ({ticker, start=0, limit=500}) {
    let self = this;
    let url = `${rpc}/v1/indexer/brc20/${ticker}/holders?start=${start}&limit=${limit}`;
    
    const response = await fetch(url, {
        method: 'GET',
        headers: self.headers,
        agent: self.agent
      });
      let res = await response.json();
      return res.data.detail;

}

UnisatAPI.prototype.get = async function (path, params) {

}


module.exports = UnisatAPI;